package com.leetcode.partition1;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author `RKC`
 * @date 2021/8/16 9:06
 */
public class LC94二叉树的中序遍历 {

    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> answer = new ArrayList<>();
        iteration(root, answer);
        return answer;
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1, new TreeNode(2), new TreeNode(3));
        n1.left.left = new TreeNode(4);
        n1.left.right = new TreeNode(5);
        n1.right.left = new TreeNode(6);
        System.out.println(inorderTraversal(n1));
    }

    private static void iteration(TreeNode root, List<Integer> answer) {
        if (root == null) return;
        Stack<TreeNode> s = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !s.isEmpty()) {
            if (cur != null) {
                //把根结点和左子节点全部入栈
                s.push(cur);
                cur = cur.left;
                continue;
            }
            //cur指向了最下角的叶子结点
            cur = s.pop();
            answer.add(cur.val);
            cur = cur.right;
        }
    }

    private static void recursion(TreeNode root, List<Integer> answer) {
        if (root == null) return;
        recursion(root.left, answer);
        answer.add(root.val);
        recursion(root.right, answer);
    }
}
